package com.hui.server.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hui.server.entity.Admin;
import com.hui.server.service.AdminService;
import com.hui.server.util.FileUtil;
import com.hui.server.util.Result;
import com.mysql.cj.util.StringUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @BelongsProject: yeb
 * @BelongsPackage: com.hui.server.controller
 * @Author: HUI
 * @CreateTime: 2022-04-16 15:58
 * @Description: 更新用户信息，查看用户信息可以在 LoginController的getAdminInfo()方法
 */

@Controller
@RequestMapping("/admin")
@Slf4j
public class AdminInfoController {

    private final AdminService adminService;

    @Value("${server.port}")//拿到配置文件的的属性
    private String port;

    @Autowired
    public AdminInfoController(AdminService adminService) {
        this.adminService = adminService;
    }


    @ApiOperation(value = "更新当前用户信息")
    @PutMapping("/info")
    @ResponseBody
    public Result<?> updateAdmin(@RequestBody Admin admin, Authentication authentication) {
        //更新成功,重新构建Authentication对象
        boolean update = adminService.updateById(admin);
        if (update) {
            /**
             * 1.用户对象
             * 2.凭证（密码）
             * 3.用户角色
             */
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(admin, authentication.getCredentials(), authentication.getAuthorities()));
            return Result.success();
        }
        return Result.error(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()), "更新失败");
    }


    @ApiOperation(value = "更新用户密码")
    @PutMapping("/pass")
    @ResponseBody
    public Result<?> updateAdminPassword(@RequestBody Map<String, Object> info) {
        log.info("进入修改密码接口");
        String oldPass = (String) info.get("oldPass");
        String pass = (String) info.get("pass");
        Integer adminId = (Integer) info.get("adminId");
        return adminService.updatePassword(oldPass, pass, adminId);
    }


    @ApiOperation(value = "更新用户头像")
    @ApiImplicitParams({@ApiImplicitParam(name = "file", value = "头像", dataType = "MultipartFile")})
    @PutMapping("/uploadface")
    @ResponseBody
    public Result<?> updateUserFace(MultipartFile file, Integer id, Authentication authentication) {

        if (!ObjectUtils.isEmpty(file) || !StringUtils.isNullOrEmpty(port)) {
            String addr = FileUtil.uploadFile(file, port);
            boolean update = adminService.update(new UpdateWrapper<Admin>().set("userFace", addr).eq("id", id));
            if (update){
                Admin admin = (Admin) authentication.getPrincipal();
                admin.setUserFace(addr);
                //更新Authentication
                SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(admin,authentication.getCredentials(),authentication.getAuthorities()));
                return Result.success(addr);
            }

        }

        return Result.error(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()), "更新失败！");
    }

    @ApiOperation(value = "获取用户头像")
    @PutMapping("/downloadface/{filename}")
    public void downloadUserFace(@PathVariable("filename") String filename, HttpServletResponse response) {
        String filePath = FileUtil.downloadFile(filename);
        BufferedInputStream bs;//缓冲流对象
        FileInputStream fs;//输入流对象
        OutputStream os;  // 新建一个输出流对象


        if (!filePath.isBlank()) {

            try {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filePath, StandardCharsets.UTF_8));
//                response.setContentType("application/octet-stream");

                response.setContentType("image/jpeg");
                fs = new FileInputStream(filePath);//通过文件的路径读取文件字节流
                bs = new BufferedInputStream(fs);//存入缓存流

                os = response.getOutputStream();// 通过输出流返回文件

                os.write(bs.readAllBytes());


                os.flush();
                os.close();
                fs.close();
                bs.close();


            } catch (FileNotFoundException e) {
                log.error("读取字节流时发生错误！");
                e.printStackTrace();

            } catch (IOException e) {
                log.error("写入缓冲流时发生错误！");
                e.printStackTrace();

            }


        } else {
            log.error("没有该文件！");
        }
    }


}
